package com.edu.nchu.study.service.impl;

import com.edu.nchu.study.model.DataSet;
import com.edu.nchu.study.service.DataSetService;
import com.edu.nchu.study.service.repo.DataSetMapper;
import com.edu.nchu.study.utils.BootConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

@Slf4j
@Service
public class DataSetServiceImpl implements DataSetService {

    @Autowired
    private DataSetMapper dataSetMapper;
    @Autowired
    private DataSource primaryDataSource;

    @Override
    public DataSet getDataSetByCode(String code) {
        DataSet ds = new DataSet();
        ds.setCode(code);
        return dataSetMapper.selectOne(ds);
    }

    @Override
    public DataSet addDataSet(DataSet dataSet) {
        return null;
    }

    @Override
    public void createDataSet(DataSet dataSet) {
        try {
            Connection connection = primaryDataSource.getConnection();
            Statement statement = connection.createStatement();
            String createSetSQL = String.format(BootConstants.MYSQL_CREATE_DATABASE_FORMAT
                    , dataSet.getCode());
            boolean createRet = statement.execute(createSetSQL);
            if (createRet) {
                log.info("create dataset successful");
            } else {
                log.info("create dataset error");
            }
        } catch (SQLException throwables) {
            log.error("create one dataset error", throwables);
        } catch (Exception e) {
            log.error("create unhandle error", e);
        }
    }
}
